// 创建birds.js
var express = require('express')
var postApi = express.Router()// 创建一个路由实例
var multiparty = require("multiparty");
const fs = require('fs');
const path = require('path');

// 中间件功能
postApi.use(function timeLog(req, res, next) {
  console.log('Time: ', new Date().toLocaleString())
  next()
})
// 访问/postApi
postApi.post('/postTest', function (req, res) {
  console.log('zdy-----headers：------>' + JSON.stringify(req.headers))
  console.log('zdy-----path------>' + JSON.stringify(req.path))
  console.log('zdy-----baseUrl------>' + JSON.stringify(req.baseUrl))
  let requestPath = ''
  if (req.baseUrl != undefined && req.baseUrl != '' && req.baseUrl != null && req.baseUrl.trim().length > 0) {
    requestPath = req.baseUrl
  } else if (req.path != undefined && req.path != '' && req.path != null && req.path.trim().length > 0) {
    requestPath = req.path
  }
  let requestUrl = ''
  if ('http' === req.protocol) {
    requestUrl = 'http://' + req.hostname + requestPath
  } else {
    requestUrl = 'https://' + req.hostname + requestPath
  }
  console.log('zdy-----requestUrl------>' + requestUrl)
  console.log('zdy-----body------>' + JSON.stringify(req.body))

  let responseMsg = '请求：' + requestUrl + '成功'
  res.json({
    header: req.headers,
    body: req.body,
    method: req.method,
    url: req.baseUrl,
    msg: responseMsg
  })
})

// 访问/uploadGzipFile
postApi.post('/multipartTest', function (req, res) {
  console.log('zdy-----headers：------>' + JSON.stringify(req.headers))
  const form = new multiparty.Form()
  form.parse(req, (err, field, files) => {
    try {
      console.log('-----field------>' + JSON.stringify(field));
      console.log('-----files------>' + JSON.stringify(files));
      if (err) {
        console.log('zdy-----err------>' + JSON.stringify(err));
        res.send(err);
        return;
      }
      if (!fs.existsSync('./public/upload')) {
        fs.mkdirSync('./public/upload')
      }
      if (files && Object.keys(files).length === 0) {
        console.log('zdy-----没有上传文件------>');
        res.send('-----没有上传文件------>');
        return;
      }

      writeFileByfs(files).then((data) => {
        console.log('zdy-----writeFileByfs  data------>' + JSON.stringify(data));
        console.log('zdy-----writeFileByfs  data typeof------>' + (data instanceof Array));
        res.status(200)
        res.send({
          header: req.headers,
          body: req.body,
          method: req.method,
          fieldBack: field,
          filesBack: files,
          url: req.originalUrl,
          msg: "上传成功"
        })
      }).catch((err) => {
        console.log('zdy-----writeFileByfs JSON err------>' + JSON.stringify(err));
        console.log('zdy-----writeFileByfs  err------>' + err);
        res.status(400)
        res.send("上传失败")
      })

    } catch (error) {
      console.log('zdy-----JSON error------>' + JSON.stringify(error));
      console.log('zdy-----writeFileByfs  error------>' + error);
      res.send(error);
    }



  })
})

function writeFileByfs(files) {
  let keys = Object.keys(files)
  console.log('zdy-----writeFileByfs  keys------>' + JSON.stringify(keys));
  let promises = [];
  function generatePromise(file) {
    return new Promise((resolve, reject) => {
      const fileName = file.originalFilename;
      console.log('zdy-----writeFileByfs  fileName------>' + fileName);
      const filePath = file.path;
      let writePath = "./public/upload/" + fileName;
      if (!fs.existsSync(writePath)) {
        fs.writeFileSync(writePath, '', 'utf-8');
      }
      const writeable = fs.createWriteStream(writePath);
      const readable = fs.createReadStream(filePath);
      readable.pipe(writeable);
      readable.on('end', () => {
        resolve(true);
      })
      readable.on('err', () => {
        reject(false);
      })
    })
  }
  for (let i = 0; i < keys.length; i++) {
    console.log('\r\n');
    console.log('\r\n');
    console.log('zdy-----writeFileByfs  keys[i]------>' + JSON.stringify(keys[i]));
    let tempFile = files[keys[i]]
    console.log('zdy-----writeFileByfs  tempFile------>' + JSON.stringify(tempFile));
    console.log('\r\n');
    for(let j = 0; j < tempFile.length; j++){
      promises.push(generatePromise(tempFile[j]))
    }
   
  }
  return Promise.all(promises);
}


module.exports = postApi